<template>
  <div ref="chartsRef" v-loading="loading" class="charts-wrap"></div>
</template>

<script setup lang="ts">
import { computed, onUnmounted, ref } from 'vue'
import * as echarts from 'echarts'
import useFetch from '@/hooks/useFetch'
import { fitChartSize, tooltipOptions } from '@screen/utils/charts'
import { getAllDomainViewMatterStatus } from '@screen/apis'
import { generatePageParams } from '@screen/utils'

const chartsRef = ref<HTMLDivElement>(null)

const defaultFillArr = new Array(15).fill(2)

const defaultSeries = ref([
  {
    data: defaultFillArr,
    barWidth: fitChartSize(16),
    type: 'bar',
    stack: 'Ad',
    name: '正常推进',
    itemStyle: {
      color: 'rgba(21, 154, 255, 1)',
    },
  },
  {
    data: defaultFillArr,
    type: 'bar',
    stack: 'Ad',
    name: '已完成',
    itemStyle: {
      color: 'rgba(102, 225, 223, 1)',
    },
  },
  {
    data: defaultFillArr,
    type: 'bar',
    stack: 'Ad',
    name: '未签收',
    itemStyle: {
      color: 'rgba(208, 222, 238, 1)',
    },
  },
  {
    data: defaultFillArr,
    type: 'bar',
    stack: 'Ad',
    name: '已超时',
    itemStyle: {
      color: 'rgba(255, 201, 122, 1)',
    },
  },
])

const maxTotal = ref(1)

let currentIndex = -1
let timer = null

const options = computed(() => ({
  grid: {
    top: '15%',
    left: (maxTotal.value + '').length < 100 ? '5%' : '10%',
    right: '0%',
    bottom: '25%',
  },
  tooltip: {
    ...tooltipOptions,
    trigger: 'axis',
    axisPointer: {
      type: 'shadow',
    },
    extraCssText: `z-index:100;`,
    formatter: (params: any) => {
      if (!params?.length) return ''
      let title = params[0].name
      const tip = params.reduce((acc, cur) => {
        return `${acc}<br>${cur.seriesName}：${cur.value}`
      }, '')
      return `${title}${tip}`
    },
  },
  legend: {
    top: '5%',
    show: true,
    textStyle: {
      fontSize: fitChartSize(12),
      color: 'rgba(208, 222, 238, 1)',
    },
    itemGap: fitChartSize(15), // 增加图例项间距
    itemStyle: {
      borderWidth: 0,
    },
    itemWidth: fitChartSize(8),
    itemHeight: fitChartSize(8),
  },
  xAxis: {
    type: 'category',
    data: [
      '重点项目',
      '园区发展',
      '深化改革',
      '文化旅游',
      '城市建设',
      '农业农村',
      '生态环境保护',
      '教育领域',
      '民生服务',
      '卫生健康',
      '人才工作',
      '人力社保',
      '平安稳定',
      '交通运输',
      '纪检监察',
    ],
    axisLabel: {
      rotate: 60,
      interval: 0,
      color: '#fff',
      fontSize: fitChartSize(12),
      fontWeight: fitChartSize(400),
      margin: fitChartSize(8), // 增加标签与轴线距离
    },
    axisPointer: {
      type: 'shadow',
    },
    axisLine: {
      lineStyle: {
        color: 'rgba(108, 128, 151, 1)',
      },
    },
    axisTick: {
      alignWithLabel: true,
    },
  },
  yAxis: [
    {
      type: 'value',
      name: '事项数(件)',
      min: 0,
      max: maxTotal.value,
      interval: Math.floor(maxTotal.value / 5),
      nameTextStyle: {
        color: 'rgba(108, 128, 151, 1)',
        fontSize: fitChartSize(12),
      },
      axisLabel: {
        color: '#6C8097',
        fontSize: fitChartSize(12),
        formatter: '{value}',
        fontFamily: 'DDin, sans-serif',
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: 'rgba(108, 128, 151, 0.63)',
        },
      },
    },
    {
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
    },
  ],
  dataZoom: [
    {
      type: 'inside',
    },
  ],
  series: defaultSeries.value,
}))

const charts = ref(null)

const { loading, onFetchSuccess } = useFetch(
  getAllDomainViewMatterStatus,
  generatePageParams(),
  true,
)

onFetchSuccess((data) => {
  let normalArr = [],
    timeoutArr = [],
    completedArr = [],
    notSignArr = []
  if (data?.length) {
    data.forEach((item) => {
      const curList = item.list
      const notAssignCounts = curList.find(
        (numItem) => numItem.type === 'notSigned',
      )
      const timeoutCounts = curList.find(
        (numItem) => numItem.type === 'timeOut',
      )
      const completedCounts = curList.find(
        (numItem) => numItem.type === 'completed',
      )
      const normalCounts = curList.find((numItem) => numItem.type === 'normal')
      const curTotle =
        (normalCounts?.number ?? 0) +
        (timeoutCounts?.number ?? 0) +
        (completedCounts?.number ?? 0) +
        (notAssignCounts?.number ?? 0)

      maxTotal.value = Math.max(maxTotal.value, curTotle)

      normalArr.push(normalCounts?.number ?? 0)
      timeoutArr.push(timeoutCounts?.number ?? 0)
      completedArr.push(completedCounts?.number ?? 0)
      notSignArr.push(notAssignCounts?.number ?? 0)
    })
  }
  defaultSeries.value[0].data = normalArr
  defaultSeries.value[1].data = timeoutArr
  defaultSeries.value[2].data = completedArr
  defaultSeries.value[3].data = notSignArr
  initCharts()
})

const initCharts = () => {
  if (charts.value) {
    charts.value.setOption(options.value)
    return
  }
  if (chartsRef?.value) {
    const chart = echarts.init(chartsRef.value)
    chart.setOption(options.value)
    charts.value = chart
    // 自动选中
    autoSelected()
    // 窗口变化自适应
    window.addEventListener('resize', handleResize)
  }
}

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  charts.value = null
  stopAutoPlay()
  currentIndex = 0
})

const handleResize = () => {
  charts.value?.resize()
}

function autoSelected() {
  // 开始自动切换
  startAutoPlay()

  // 鼠标悬停时停止自动切换
  charts.value.on('mouseover', handleMouseover, false)

  // 鼠标离开时重新开始自动切换
  charts.value.on('mouseout', handleMouseout, false)
}

function handleMouseover() {
  stopAutoPlay()
}

function handleMouseout() {
  startAutoPlay()
}

function autoHighlight() {
  // 清除之前的高亮
  charts.value.dispatchAction({
    type: 'downplay',
    seriesIndex: 0,
    dataIndex: currentIndex,
  })

  const dataLength = options.value.series[0].data?.length
  // 计算下一个索引
  currentIndex = (currentIndex + 1) % dataLength

  // 应用新的高亮
  charts.value.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: currentIndex,
  })

  // 显示提示框
  charts.value.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: currentIndex,
  })
}

// 开始自动切换
function startAutoPlay() {
  if (timer) {
    clearInterval(timer)
  }
  timer = setInterval(autoHighlight, 1000) // 2秒切换一次
}

// 停止自动切换
function stopAutoPlay() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
}
</script>

<style lang="scss" scoped>
.charts-wrap {
  width: vw(851);
  height: vh(378);
}
</style>
